var form = layui.form;

let q = {
  start_time: '',
  end_time: '',
  title: '',
  cateid: '',
  page: '1',
  limit: '10',
};

// 一般当表单存在动态生成时，进行渲染
form.render(); // 渲染全部

//日期
layui.use(['form', 'layer', 'laydate'], function () {
  var form = layui.form, layer = layui.layer, laydate = layui.laydate;
  //日期
  var start = laydate.render({
    elem: '#startDate',
    type: 'date',
    done: function (value, date) {
      endMax = end.config.max;
      end.config.min = date;
      end.config.min.month = date.month - 1;
    }
  });
  var end = laydate.render({
    elem: '#endDate',
    type: 'date',
    done: function (value, date) {
      if ($.trim(value) == '') {
        var curDate = new Date();
        date = {
          'date': curDate.getDate(),
          'month': curDate.getMonth() + 1,
          'year': curDate.getFullYear()
        };
      }
      start.config.max = date;
      start.config.max.month = date.month - 1;
    }
  })
})

function getselsect() {
  $.ajax({
    url: 'http://124.223.14.236:8060/admin/ydd_cate/all',
    method: 'GET',
    headers: {
      'x-token': localStorage.getItem('x-token'),
    },
    success(res) {
      const re2 = res.data.map(item => {
        return `<option value="${item.id}">${item.catename}</option></dd>`
      }).join('')
      $('#select_one').append(re2)
      form.render();
      q.cateid = res.data.id
    }
  })
}
getselsect()


let count = 0
//封装主页表格渲染函数
function rander() {
  $.ajax({
    url: 'http://124.223.14.236:8060/admin/ydd_article/list',
    method: 'GET',
    headers: {
      'x-token': localStorage.getItem('x-token'),
    },
    data: q,
    success(res) {
      console.log(res.data.count);
      count = res.data.count
      const str = res.data.data.map(item => {
        let hot = item.ishot ? '<i class="layui-icon hot_xin" style="font-size: 20px; color: #1E9FFF;">&#xe658;</i>' : '<i class="layui-icon hot_xin" style="font-size: 20px;">&#xe600;</i>'
        let top = item.istop ? '<i class="layui-icon top_xin" style="font-size: 20px; color: #1E9FFF;">&#xe658;</i>' : '<i class="layui-icon top_xin" style="font-size: 20px;">&#xe600;</i>'
        return `<tr>
                  <td class="xl_one1">${item.id}</td>
                  <td class="xl_one2">${item.title}</td>
                  <td class="xl_one3">${item.catename}</td>
                  <td class="xl_one4">
                    <img src="http://124.223.14.236:8060/${item.pic}" alt="">
                  </td>
                  <td class="xl_one5">${getDate(item.create_date)}</td>
                  <td class="xl_one6 ">${hot}</td>
                  <td class="xl_one7 ">${top}</td>
                  <td class="xl_one8">
                    <button type="button" class="layui-btn layui-btn-primary">已发布</button>
                  </td>
                  <td class="xl_one9">
                    <button type="button" class="layui-btn layui-btn-normal change_btn" data-id='${item.id}'>修改</button>
                    <button type="button" class="layui-btn layui-btn-danger del_btn" data-id='${item.id}'>删除</button>
                  </td>
                </tr>
        
        `
      })
      $('#tbody').html(str)
      getPaging(count)
    }

  })
}
rander()

//封装转换时间函数
function getDate(date) {
  const time = new Date(date)
  const y = time.getFullYear()
  let m = time.getMonth()
  let d = time.getDate()

  let hh = time.getHours()
  let mm = time.getMinutes()
  let ss = time.getSeconds()
  return `${y}-${buling(m)}-${buling(d)} ${buling(hh)}:${buling(mm)}:${buling(ss)}`
}
//封装补零函数
function buling(a) {
  return a > 9 ? a : '0' + 9
}

//分页功能


function getPaging(count) {
  layui.use('laypage', function () {
    var laypage = layui.laypage;
    //执行一个laypage实例
    laypage.render({
      elem: 'pag', //注意，这里的 test1 是 ID，不用加 # 号
      count: count, //数据总数，从服务端得到
      limit: q.limit,
      curr: q.page,
      limits: [10, 8, 6, 4, 2],
      layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
      jump: function (obj, first) {
        q.page = obj.curr;
        q.limit = obj.limit;
        if (!first) {
          console.log(q.page, q.limit);
          rander()

        }
      },
    });
  });
}

//刷新按钮
$('#reset_btn').on('click', function () {
  q.start_time = ''
  q.end_time = ''
  q.title = ''
  q.cateid = ''
  rander()
  $('#title_ipt').val('')
})

//搜索按钮
$('#search_btn').on('click', function () {
  q.start_time = Date.parse($('#startDate').val())
  q.end_time = Date.parse($('#endDate').val()) || +new Date()
  q.title = $('#title_ipt').val()
  q.cateid = $('#select_one').val()
  rander()
})

$('#shuaxin_btn').click(function () {
  $('#reset_btn').click()
})

$('.show_btn').click(function () {
  $('.layui-card-header').slideToggle()
  $(this).hide().siblings().show()
})

$('#addArticle').on('click', function () {
  $('#one_box').hide()
  $('#two_box').show()
})

$('#file_btn').on('click', function () {
  $('#addFile').click()
})

$('.back_list').on('click', function () {
  $('#one_box').show()
  $('#two_box').hide()
})
$('.stoptip').on('submit', function (e) {
  e.preventDefault()
})

//上传图片
$('#addFile').on('change', function () {
  const fd = new FormData()
  fd.append('file', $('#addFile')[0].files[0])
  $.ajax({
    url: 'http://124.223.14.236:8060/common/upload?type=images',
    method: 'POST',
    data: fd,
    headers: {
      token: localStorage.getItem('x-token'),
    },
    contentType: false,
    processData: false,
    success: function (res) {
      console.log(res);
      console.log(res.data.savePath);
      $('#pic_kg img').prop('src', `http://124.223.14.236:8060/${res.data.savePath}`)
    },
  });
})


//提交文章模块
$('#two_form').on('submit', function (e) {
  e.preventDefault()
  const title = $('#two_form [name=title]').val()
  const author = $('#two_form [name=author]').val()
  const lovenum = $('#two_form [name=lovenum]').val()
  const click = $('#two_form [name=click]').val()
  const tags = $('#tag_btn [name=like]:checked').attr('title')
  const create_date = Date.parse($('#two_form [name=create_date]').val())
  const keywords = $('#two_form [name="keywords"]').val()
  const description = $('#two_form [name="description"]').val()
  const content = $('#two_form [name="content"]').val()
  const pic = $('#pic_kg img').prop('src').substr(27)
  const cate = $('#two_form [name=catename]').val()
  console.log(pic);
  console.log(cate);
  let ishot = $('#two_form [name=ishot]').prop('checked') ? 1 : 0
  let istop = $('#two_form [name=istop]').prop('checked') ? 1 : 0
  $.ajax({
    url: 'http://124.223.14.236:8060/admin/ydd_article/add',
    method: 'POST',
    headers: {
      'x-token': localStorage.getItem('x-token'),
    },
    data: {
      title: title,
      author: author,
      city: cate,
      cateid: cate,
      click: click,
      tags: tags,
      lovenum: lovenum,
      create_date: create_date,
      ishot: ishot,
      istop: istop,
      keywords: keywords,
      description: description,
      content: content,
      pic: pic
    },
    success(res) {
      $('#reset_formbtn').click()
      layer.msg('添加成功')
      $('.back_list').click()
      rander()
    }
  })
})


//删除
$('body').on('click', '.del_btn', function () {
  const id = $(this).attr('data-id')
  layer.confirm('真的要删除该数据吗？', { title: "删除确认" }, function (index) {
    //具体逻辑
    $.ajax({
      url: 'http://124.223.14.236:8060/admin/ydd_article/del',
      method: 'GET',
      headers: {
        'x-token': localStorage.getItem('x-token'),
      },
      data: {
        id: id
      },
      success(res) {
        layer.msg('删除成功')
        rander()
      }
    })
  })
})


//控制表单列显示
$('.check').prop('checked', true);
let btns = document.querySelectorAll('.check');
for (let i = 0; i < btns.length; i++) {
  btns[i].setAttribute('index', i);
  btns[i].onclick = function () {
    index = this.getAttribute('data-checked');
    console.log(index);
    if (index == 0) {
      $('.xl_one1').toggleClass('all');
    } else if (index == 1) {
      $('.xl_one2').toggleClass('all');
    } else if (index == 2) {
      $('.xl_one3').toggleClass('all');
    } else if (index == 3) {
      $('.xl_one4').toggleClass('all');
    } else if (index == 4) {
      $('.xl_one5').toggleClass('all');
    } else if (index == 5) {
      $('.xl_one6').toggleClass('all');
    } else if (index == 6) {
      $('.xl_one7').toggleClass('all');
    } else if (index == 7) {
      $('.xl_one8').toggleClass('all');
    } else if (index == 8) {
      $('.xl_one9').toggleClass('all');
    }
  };
  rander()
}

$('#check_btn').on('click', function () {
  $('.adv-box').toggle()
})

//导出
$('#export').click(function (e) {
  var table = $('.layui-table');
  var preserveColors = table.hasClass('table2excel_with_colors') ? true : false;
  $(table).table2excel({
    exclude: '.noExl',
    name: 'Excel Document Name',
    filename: 'myFileName' + new Date().toISOString().replace(/[\-\:\.]/g, '') + '.xls',
    fileext: '.xls',
    exclude_img: true,
    exclude_links: true,
    exclude_inputs: true,
    preserveColors: preserveColors,
  });
});

//获取cateid 
function getCateId() {
  $.ajax({
    url: 'http://124.223.14.236:8060/admin/ydd_cate/all',
    method: 'GET',
    headers: {
      'x-token': localStorage.getItem('x-token'),
    },
    success(res) {
      const re2 = res.data.map(item => {
        return `<option value="${item.id}">${item.catename}</option></dd>`
      }).join('')
      $('#select').append(re2)
      form.render();
    }
  })
}
getCateId()


//修改按钮
$('body').on('click', '.change_btn', function () {
  id = $(this).attr('data-id')
  $.ajax({
    url: 'http://124.223.14.236:8060/admin/ydd_article/rowInfo?id=608',
    method: 'GET',
    headers: {
      'x-token': localStorage.getItem('x-token'),
    },
    data: {
      id: $(this).attr('data-id')
    },
    success(res) {
      console.log(res.data);
      $('#addArticle').click()
      $('#two_form [name=title]').val(res.data.title)
      $('#two_form [name=author]').val(res.data.author)
      $('#two_form [name=lovenum]').val(res.data.lovenum)
      $('#two_form [name=click]').val(res.data.click)
      // $('#tag_btn [name=like]:checked').attr('title', res.data.tags)
      $('#two_form [name=create_date]').val(getDate(res.data.create_date))
      $('#two_form [name="keywords"]').val(res.data.keywords)
      $('#two_form [name="description"]').val(res.data.description)
      $('#two_form [name="content"]').val(res.data.content)
      $('#pic_kg img').prop('src', `http://124.223.14.236:8060/${res.data.pic}`)
      $('#two_form [name=catename]').val(res.data.cateid)
      // let ishot = $('#two_form [name=ishot]').prop('checked') ? 1 : 0
      // let istop = $('#two_form [name=istop]').prop('checked') ? 1 : 0
      // $(this).parent().siblings('.xl_one6 ').children('.hot_xin').css('color', '')
      $('#two_form [name=ishot]').prop('checked', `${res.data.ishot ? true : false}`)
      $('#two_form [name=istop]').prop('checked', `${res.data.istop ? true : false}`)
      form.render()
      $('.change_btn_form').show()
      $('.set_btn').hide()
    }
  })
})
//color: #1E9FFF;

$('.change_btn_form').on('click', function (e) {
  e.preventDefault()
  const title = $('#two_form [name=title]').val()
  const author = $('#two_form [name=author]').val()
  const lovenum = $('#two_form [name=lovenum]').val()
  const click = $('#two_form [name=click]').val()
  const tags = $('#tag_btn [name=like]:checked').attr('title')
  const create_date = Date.parse($('#two_form [name=create_date]').val())
  const keywords = $('#two_form [name="keywords"]').val()
  const description = $('#two_form [name="description"]').val()
  const content = $('#two_form [name="content"]').val()
  const pic = $('#pic_kg img').prop('src').substr(27)
  const cate = $('#two_form [name=catename]').val()
  let ishot = $('#two_form [name=ishot]').prop('checked') ? 1 : 0
  let istop = $('#two_form [name=istop]').prop('checked') ? 1 : 0
  $.ajax({
    url: 'http://124.223.14.236:8060/admin/ydd_article/update',
    method: 'POST',
    headers: {
      'x-token': localStorage.getItem('x-token'),
    },
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({
      id: +id,
      title: title,
      author: author,
      keywords: keywords,
      description: description,
      content: content,
      pic: pic,
      click: click,
      ishot: ishot,
      istop: istop,
      update_date: create_date,
      cateid: cate,
      tags: tags,
      status: 2,
      lovenum: lovenum,
      default_data: "0"
    }),
    success(res) {
      // if (res.Status Code !== 200) return layer.msg('更新失败')
      $('.change_btn_form').hide()
      $('.set_btn').show()
      $('#reset_formbtn').click()
      $('.back_list').click()
      layer.msg('更新成功')
      rander()
    }
  })
})



